/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.wms.web;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.infor.entity.Position;
import com.jeeplus.modules.infor.entity.Staff;
import com.jeeplus.modules.infor.service.PositionService;
import com.jeeplus.modules.infor.service.StaffService;
import com.jeeplus.modules.sys.utils.UserUtils;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.wms.entity.WorkStatistics;
import com.jeeplus.modules.wms.service.WorkStatisticsService;

/**
 * 作业量统计Controller
 * @author 李超辉
 * @version 2018-07-13
 */
@Controller
@RequestMapping(value = "${adminPath}/wms/workStatistics")
public class WorkStatisticsController extends BaseController {

	@Autowired
	private WorkStatisticsService workStatisticsService;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private PositionService positionService;
	@Autowired
	private StaffService staffService;
	@ModelAttribute
	public WorkStatistics get(@RequestParam(required=false) String id) {
		WorkStatistics entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workStatisticsService.get(id);
		}
		if (entity == null){
			entity = new WorkStatistics();
		}
		return entity;
	}
	
	/**
	 * 作业量统计列表页面
	 */
	@RequiresPermissions("wms:workStatistics:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/wms/workStatisticsList";
	}
	
		/**
	 * 作业量统计列表数据
	 */
	@ResponseBody
	@RequiresPermissions("wms:workStatistics:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(WorkStatistics workStatistics, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			workStatistics.setPro(pro);
		}
		Page<WorkStatistics> page = workStatisticsService.findPage(new Page<WorkStatistics>(request, response), workStatistics);
		return getBootstrapData(page);
	}

	@ResponseBody
	@RequestMapping(value="cx")
	public String cx(String min,String max,String pro,String name){
		if(min==""&max==""){
			return "";
		}
		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
			cha(min,max,pro,name);
		}else{
			cha(min,max, UserUtils.getUseroffice(),name);
		}
		return "";
	}

	public void cha(String min,String max,String pro,String name){
		String sql;
		String sq;
		String s;
		if(!pro.equals("总部")){
			if(name!=null&&!name.equals("")){
				sql="SELECT p.pro as pro, p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.dg) AS dg,SUM(p.dx) AS dx,SUM(p.xht) AS xht,SUM(p.xx) AS xx,SUM(p.xt) AS xt,SUM(p.zt) AS zt,SUM(p.dt) AS dt,SUM(p.dai) AS dai,SUM(p.jian) AS jian FROM `wms_statistics` p WHERE to_days(p.create_date)>= to_days('"+min+"') and to_days(p.create_date)< to_days('"+max+"') and p.pro='"+pro+"' and p.name='"+name+"'  GROUP BY p.pro, p.type,p.NAME ,p.position";
				sq="SELECT p.pro as pro, p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.dg) AS dg,SUM(p.dx) AS dx,SUM(p.xht) AS xht,SUM(p.xx) AS xx,SUM(p.xt) AS xt,SUM(p.zt) AS zt,SUM(p.dt)AS dt ,SUM(p.dai) AS dai,SUM(p.jian) AS jian FROM `wms_outstatistics` p WHERE to_days(p.create_date)>= to_days('"+min+"') and to_days(p.create_date)< to_days('"+max+"') and p.pro='"+pro+"'  and p.name='"+name+"' GROUP BY p.pro, p.type,p.NAME ,p.position";
			}else {
				sql = "SELECT p.pro as pro, p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.dg) AS dg,SUM(p.dx) AS dx,SUM(p.xht) AS xht,SUM(p.xx) AS xx,SUM(p.xt) AS xt,SUM(p.zt) AS zt,SUM(p.dt)AS dt ,SUM(p.dai) AS dai,SUM(p.jian) AS jian  FROM `wms_statistics` p WHERE to_days(p.create_date)>= to_days('" + min + "') and to_days(p.create_date)< to_days('" + max + "') and p.pro='" + pro + "' GROUP BY p.pro, p.type,p.NAME ,p.position";
				sq = "SELECT p.pro as pro, p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.dg) AS dg,SUM(p.dx) AS dx,SUM(p.xht) AS xht,SUM(p.xx) AS xx,SUM(p.xt) AS xt,SUM(p.zt) AS zt,SUM(p.dt)AS dt ,SUM(p.dai) AS dai,SUM(p.jian) AS jian  FROM `wms_outstatistics` p WHERE to_days(p.create_date)>= to_days('" + min + "') and to_days(p.create_date)< to_days('" + max + "') and p.pro='" + pro + "' GROUP BY p.pro, p.type,p.NAME ,p.position";
			} s="delete from wms_work_statistics where pro='"+pro+"'";
		}else{
			if(name!=null&&!name.equals("")){
				sql = "SELECT p.pro as pro, p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.dg) AS dg,SUM(p.dx) AS dx,SUM(p.xht) AS xht,SUM(p.xx) AS xx,SUM(p.xt) AS xt,SUM(p.zt) AS zt,SUM(p.dt)AS dt  ,SUM(p.dai) AS dai,SUM(p.jian) AS jian FROM `wms_statistics` p WHERE to_days(p.create_date)>= to_days('" + min + "') and to_days(p.create_date)< to_days('" + max + "') and p.name='"+name+"' GROUP BY p.type,p.NAME,p.position ";
				sq = "SELECT p.pro as pro, p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.dg) AS dg,SUM(p.dx) AS dx,SUM(p.xht) AS xht,SUM(p.xx) AS xx,SUM(p.xt) AS xt,SUM(p.zt) AS zt,SUM(p.dt)AS dt ,SUM(p.dai) AS dai,SUM(p.jian) AS jian  FROM `wms_outstatistics` p WHERE to_days(p.create_date)>= to_days('" + min + "') and to_days(p.create_date)< to_days('" + max + "') and p.name='"+name+"' GROUP BY p.type,p.NAME,p.position";

			}else {
				sql = "SELECT p.pro as pro, p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.dg) AS dg,SUM(p.dx) AS dx,SUM(p.xht) AS xht,SUM(p.xx) AS xx,SUM(p.xt) AS xt,SUM(p.zt) AS zt,SUM(p.dt)AS dt ,SUM(p.dai) AS dai,SUM(p.jian) AS jian  FROM `wms_statistics` p WHERE to_days(p.create_date)>= to_days('" + min + "') and to_days(p.create_date)< to_days('" + max + "')  GROUP BY p.type,p.NAME ,p.position";
				sq = "SELECT p.pro as pro, p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.dg) AS dg,SUM(p.dx) AS dx,SUM(p.xht) AS xht,SUM(p.xx) AS xx,SUM(p.xt) AS xt,SUM(p.zt) AS zt,SUM(p.dt)AS dt ,SUM(p.dai) AS dai,SUM(p.jian) AS jian  FROM `wms_outstatistics` p WHERE to_days(p.create_date)>= to_days('" + min + "') and to_days(p.create_date)< to_days('" + max + "')  GROUP BY p.type,p.NAME ,p.position";
			}s="delete from wms_work_statistics ";
		}
        jdbc.execute(s);
		List<Map<String,Object>> list=jdbc.queryForList(sql);
		List<Map<String,Object>> lis=jdbc.queryForList(sq);
		List<Map<String,Object>> maps=hb(list,lis);
		for(Map<String,Object> m:maps){
			WorkStatistics w=new WorkStatistics();
			w.setName(staffService.get(m.get("name")+"").getName());
			w.setPro(m.get("pro")+"");
			w.setPosition(m.get("position")+"");
			w.setType(m.get("type")+"");
			w.setDg(m.get("dg")+"");
			w.setDx(m.get("dx")+"");
			w.setXht(m.get("xht")+"");
			w.setXx(m.get("xx")+"");
			w.setXt(m.get("xt")+"");
			w.setZt(m.get("zt")+"");
			w.setDt(m.get("dt")+"");
			w.setDai(m.get("dai")+"");
			w.setJian(m.get("jian")+"");
			w.setOdg(m.get("dg1")+"");
			w.setOdx(m.get("dx1")+"");
			w.setOxht(m.get("xht1")+"");
			w.setOxx(m.get("xx1")+"");
			w.setOxt(m.get("xt1")+"");
			w.setOzt(m.get("zt1")+"");
			w.setOdt(m.get("dt1")+"");
			w.setOdai(m.get("dai1")+"");
			w.setOjian(m.get("jian1")+"");

			workStatisticsService.save(w);
		}
	}


	public  List<Map<String ,Object>> hb(List<Map<String ,Object>> list,List<Map<String ,Object>> lis){
		NumberFormat nf = NumberFormat.getInstance();
		List<Map<String ,Object>> list1=new ArrayList<>();
		for(Map<String,Object> m:list){
			Map<String ,Object> m1=new HashMap<>();
			boolean bo=false;
			for(Map<String,Object> map:lis){
				if(m.get("position").toString().equals(map.get("position").toString())&&m.get("type").toString().equals(map.get("type").toString())&&m.get("name").toString().equals(map.get("name").toString())&&m.get("pro").toString().equals(map.get("pro").toString())){
					bo=true;
				}
			}
			m1.put("pro",m.get("pro"));
			m1.put("name",m.get("name"));
			m1.put("type",m.get("type"));
			m1.put("dg",nf.format(m.get("dg")));
			m1.put("dx",nf.format(m.get("dx")));
			m1.put("xht",nf.format(m.get("xht")));
			m1.put("xx",nf.format(m.get("xx")));
			m1.put("xt",nf.format(m.get("xt")));
			m1.put("zt",nf.format(m.get("zt")));
			m1.put("dt",nf.format(m.get("dt")));
			m1.put("dai",nf.format(m.get("dai")));
			m1.put("jian",nf.format(m.get("jian")));
			m1.put("position",positionService.get(m.get("position").toString()).getName());
			if(bo){
				for(Map<String,Object> map:lis){
					if(m.get("position").toString().equals(map.get("position")+"")&&m.get("type").toString().equals(map.get("type").toString())&&m.get("name").toString().equals(map.get("name").toString())){
						m1.put("dg1",nf.format(map.get("dg")));
						m1.put("dx1",nf.format(map.get("dx")));
						m1.put("xht1",nf.format(map.get("xht")));
						m1.put("xx1",nf.format(map.get("xx")));
						m1.put("xt1",nf.format(map.get("xt")));
						m1.put("zt1",nf.format(map.get("zt")));
						m1.put("dt1",nf.format(map.get("dt")));
						m1.put("dai1",nf.format(map.get("dai")));
						m1.put("jian1",nf.format(map.get("jian")));
					}
				}

			}else{
				m1.put("dg1","0");
				m1.put("dx1","0");
				m1.put("xht1","0");
				m1.put("xx1","0");
				m1.put("xt1","0");
				m1.put("zt1","0");
				m1.put("dt1","0");
				m1.put("dai1","0");
				m1.put("jian1","0");
			}
			list1.add(m1);
		}
		List<Map<String ,Object>> list11=new ArrayList<>();
		for(Map<String,Object> m:lis){
			boolean bol=true;
			for(Map<String,Object> mm:list){
				if(m.get("position").toString().equals(mm.get("position")+"")&&m.get("type").toString().equals(mm.get("type").toString())&&m.get("name").toString().equals(mm.get("name").toString())&&m.get("pro").toString().equals(mm.get("pro").toString())){
					bol=false;
					break;
				}
			}
			if(bol){
				Map<String,Object> mm=new HashMap<String, Object>() ;
				mm.put("position",positionService.get(m.get("position").toString()).getName());
				mm.put("name",m.get("name"));
				mm.put("type",m.get("type"));
				mm.put("gtype",m.get("gtype"));
				mm.put("dg","0");
				mm.put("dx","0");
				mm.put("xht","0");
				mm.put("xx","0");
				mm.put("xt","0");
				mm.put("zt","0");
				mm.put("dt","0");
				mm.put("dai","0");
				mm.put("jian","0");
				mm.put("dg1",nf.format(m.get("dg")));
				mm.put("dx1",nf.format(m.get("dx")));
				mm.put("xht1",nf.format(m.get("xht")));
				mm.put("xx1",nf.format(m.get("xx")));
				mm.put("xt1",nf.format(m.get("xt")));
				mm.put("zt1",nf.format(m.get("zt")));
				mm.put("dt1",nf.format(m.get("dt")));
				mm.put("dai1",nf.format(m.get("dai")));
				mm.put("jian1",nf.format(m.get("jian")));
				mm.put("pro",m.get("pro"));

				list11.add(mm);

			}
		}
		list1.addAll(list11);
		return  list1;
	}
	/**
	 * 查看，增加，编辑作业量统计表单页面
	 */
	@RequiresPermissions(value={"wms:workStatistics:view","wms:workStatistics:add","wms:workStatistics:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkStatistics workStatistics, Model model) {
		model.addAttribute("workStatistics", workStatistics);
		return "modules/wms/workStatisticsForm";
	}

	/**
	 * 保存作业量统计
	 */
	@ResponseBody
	@RequiresPermissions(value={"wms:workStatistics:add","wms:workStatistics:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(WorkStatistics workStatistics, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, workStatistics)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		workStatisticsService.save(workStatistics);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存作业量统计成功");
		return j;
	}
	
	/**
	 * 删除作业量统计
	 */
	@ResponseBody
	@RequiresPermissions("wms:workStatistics:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(WorkStatistics workStatistics, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		workStatisticsService.delete(workStatistics);
		j.setMsg("删除作业量统计成功");
		return j;
	}
	
	/**
	 * 批量删除作业量统计
	 */
	@ResponseBody
	@RequiresPermissions("wms:workStatistics:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workStatisticsService.delete(workStatisticsService.get(id));
		}
		j.setMsg("删除作业量统计成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("wms:workStatistics:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(WorkStatistics workStatistics, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "作业量统计"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkStatistics> page = workStatisticsService.findPage(new Page<WorkStatistics>(request, response, -1), workStatistics);
    		new ExportExcel("作业量统计", WorkStatistics.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出作业量统计记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("wms:workStatistics:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WorkStatistics> list = ei.getDataList(WorkStatistics.class);
			for (WorkStatistics workStatistics : list){
				try{
					workStatisticsService.save(workStatistics);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条作业量统计记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条作业量统计记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入作业量统计失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/wms/workStatistics/?repage";
    }
	
	/**
	 * 下载导入作业量统计数据模板
	 */
	@RequiresPermissions("wms:workStatistics:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "作业量统计数据导入模板.xlsx";
    		List<WorkStatistics> list = Lists.newArrayList(); 
    		new ExportExcel("作业量统计数据", WorkStatistics.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/wms/workStatistics/?repage";
    }

}